package de.zainodis.triplog.ui.fragment;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import de.zainodis.triplog.R;
import de.zainodis.triplog.data.DataProvider;
import de.zainodis.triplog.data.WeatherEntry;
import de.zainodis.triplog.data.sync.TriplogSyncAdapter;
import de.zainodis.triplog.ui.WeatherForecastActivity;
import de.zainodis.triplog.ui.task.IAsyncTaskParent;
import de.zainodis.triplog.ui.task.WeatherLoader;
import de.zainodis.triplog.util.DateTimeUtils;
import de.zainodis.triplog.util.Utilities;

/**
 * Fragment that displays today's weather as a preview. A click on this fragment's layout opens the detail view.
 */
public class WeatherPreviewFragment extends Fragment {
    private static final String TAG = "WeatherPreviewFragment";

    private WeatherUpdateReceiver updateReceiver;

    public WeatherPreviewFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_weather_preview, container, false);
        //Listen for touch
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DataProvider.hasLocation()) {
                    Log.i(TAG, "User touched weather preview, opening weather forecast screen.");
                    startActivity(new Intent(WeatherPreviewFragment.this.getActivity(), WeatherForecastActivity.class));
                } else {
                    Log.w(TAG, "Cant show weather forecast screen, there is no location available.");
                }
            }
        });
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //Hide the weather ui until it's loaded and show the wait spinner instead
        view.findViewById(R.id.fragment_weather_preview_today).setVisibility(View.GONE);
        getView().findViewById(R.id.wait_spinner).setVisibility(View.VISIBLE);
    }

    @Override
    public void onResume() {
        super.onResume();
        updateReceiver = new WeatherUpdateReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(TriplogSyncAdapter.ACTION_WEATHER_SYNC_COMPLETE);
        getActivity().registerReceiver(updateReceiver, filter);
    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            getActivity().unregisterReceiver(updateReceiver);
        } catch (Throwable e) {
            Log.e(TAG, "Failed to unregister weather update receiver.", e);
        }
    }

    public void onUpdate(Context context) {
        new WeatherLoader(context, OnWeatherLoaded).execute();

    }

    private IAsyncTaskParent OnWeatherLoaded = new IAsyncTaskParent<WeatherEntry>() {

        @Override
        public void onPostExecute(WeatherEntry result) {
            if (getActivity() == null || getActivity().isFinishing()) {
                return;
            }
            if (result == null) {
                //TODO Show note, that weather could not be loaded
            } else {
                //Display today's weather
                View view = getView().findViewById(R.id.fragment_weather_preview_today);

                TextView dateView = (TextView) view.findViewById(R.id.list_item_forecast_date);
                dateView.setText(DateTimeUtils.getFriendlyDayString(getActivity(), result.getDate()));

                TextView summaryView = (TextView) view.findViewById(R.id.list_item_forecast_summary);
                summaryView.setText(result.getDescription());

                String unit = Utilities.getPreferredUnit(getActivity());
                boolean isMetric = getString(R.string.pref_value_metric).equals(unit);
                String min = Utilities.formatTemperature(getActivity(), Integer.valueOf(result.getMin()), isMetric);
                String max = Utilities.formatTemperature(getActivity(), Integer.valueOf(result.getMax()), isMetric);

                TextView maxView = (TextView) view.findViewById(R.id.list_item_forecast_max);
                maxView.setText(max);

                TextView minView = (TextView) view.findViewById(R.id.list_item_forecast_min);
                minView.setText(min);

                ImageView icon = (ImageView) view.findViewById(R.id.list_item_forecast_image);
                icon.setImageDrawable(getResources().getDrawable(Utilities.getWeatherIconId(result.getIconId())));

                //Hide wait spinner and show weather ui
                getView().findViewById(R.id.wait_spinner).setVisibility(View.GONE);
                view.setVisibility(View.VISIBLE);

            }
        }
    };

    public class WeatherUpdateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //The weather has changed, so now we should re-query for our weather
            onUpdate(context);
        }
    }
}
